<!-- 公共检索组件 -->
<template>
  <div class="search-form-box">
    <el-form ref="formRef" :model="formData" :inline="true" :size="formSize">
      <el-form-item
        v-for="(item, index) in formOptions"
        :key="newKeys[index]"
        class="mr20"
        :prop="item.prop"
        :label="item.label"
        :rules="item.rules"
      >
        <formItem v-model="formData[item.prop]" :item-options="item" />
      </el-form-item>

      <!-- 按钮 -->
      <template v-if="formOptions.length > 0">
        <template v-for="(item, index) in btnList">
          <el-form-item v-if="btnItems.includes(item.key)" :key="index">
            <el-button
              size="small"
              :type="item.type"
              class="mr10"
              :loading="btnLoading.includes(item.btnLoading)"
              @click="handleBtn(item)"
            >
              {{ item.btnTxet }}
            </el-button>
          </el-form-item>
        </template>
      </template>
      <span v-if="tip" class="lineHeight35 c-FF5">{{ tip }}</span>
    </el-form>
  </div>
</template>

<script>
import formItem from './commonSearchFormItem'

export default {
  components: { formItem },
  props: {
    /**
     * https://blog.csdn.net/u010059669/article/details/104038726 参考此处
     * 需要的功能可以根据elementui组件自由拓展
     * 表单配置
     * 示例：
     * [{
     * label: '用户名', // label文字
     * prop: 'username', // 字段名
     * element: 'el-input', // 指定elementui组件
     * initValue: '阿黄', // 字段初始值
     * placeholder: '请输入用户名', // elementui组件属性
     * rules: [{ required: true, message: '必填项', trigger: 'blur' }], // elementui组件属性
     * events: { // elementui组件方法
     *  input (val) {
     *  console.log(val)
     *  },
     *  ...... // 可添加任意elementui组件支持的方法
     * }
     * ...... // 可添加任意elementui组件支持的属性
     * }]
     */
    formOptions: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    formSize: {
      type: String,
      default() {
        return 'small'
      }
    },
    // 提交按钮项，多个用逗号分隔（query, export, reset）
    btnItems: {
      type: String,
      default() {
        return 'search, reset'
      }
    },
    // 加载动画，多个用逗号分隔（searchLoading, exportLoading, resetLoading
    btnLoading: {
      type: String,
      default: ''
    },
    tip: {
      type: String,
      default() {
        return ''
      }
    }
  },

  data() {
    return {
      formData: {},
      timer: null,
      timeStamp: null,
      btnList: [
        {
          btnTxet: '查询', type: 'primary', key: 'search', btnLoading: 'searchLoading'
        },
        {
          btnTxet: '导出', type: 'primary', key: 'export', btnLoading: 'exportLoading'
        },
        {
          btnTxet: '重置', type: 'default', key: 'reset', btnLoading: 'defaultLoading'
        },
        {
          btnTxet: '新增', type: 'primary', key: 'add', btnLoading: 'addLoading'
        }
      ]
    }
  },

  computed: {
    // 创建唯一的字符串
    newKeys() {
      return this.formOptions.map(v => {
        const timestamp = `${+new Date()}`
        const randomNum = `${parseInt((1 + Math.random()) * 65536, 10)}`
        return (+(randomNum + timestamp)).toString(32)
      })
    }
  },

  created() {
    this.startTimer()
    this.addInitValue()
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },

  methods: {
    startTimer() {
      this.timer = setInterval(() => {
        this.timeStamp = new Date().getTime()
      }, 1000)
    },

    // 添加初始值
    addInitValue() {
      const obj = {}
      this.formOptions.forEach(v => {
        if (v.initDateBefore !== undefined) {
          // 自定义初始时间
          obj[v.prop] = [
            new Date(this.$util.dateUtil.getBeforeDate(v.initDateBefore)),
            new Date(new Date(this.$util.dateUtil.getBeforeDate(0)).getTime() + 24 * 60 * 60 * 1000 - 1)
          ]
        }
        if (v.initValue !== undefined) {
          obj[v.prop] = v.initValue
        }
      })
      this.formData = obj
    },

    handleBtn(item) {
      this.onValidate(() => {
        switch (item.key) {
          // 查询
          case 'search':
            this.onSearch()
            break
          // 导出
          case 'export':
            this.onExport()
            break
          // 导出
          case 'reset':
            this.onReset()
            break
          default:
            this.$emit('handleBtn', item)
            break
        }
      })
    },

    // 校验
    onValidate(callback) {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          callback()
        }
      })
    },

    // 搜索
    onSearch() {
      this.onValidate(() => {
        this.$emit('onSearch', this.formData)
      })
    },

    // 导出
    onExport() {
      this.onValidate(() => {
        this.$emit('onExport', this.formData)
      })
    },

    // 重置
    onReset() {
      this.$refs.formRef.resetFields()
      this.$emit('onSearch', this.formData)
    },

    // 新增项目
    onNewProject() {
      this.onValidate(() => {
        this.$emit('onNewProject')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
